package com.conversationboard.email;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.naming.NamingException;

import com.conversationboard.config.Configuration;
import com.conversationboard.config.ConnectionStrategy;
import com.conversationboard.logger.LogMessageType;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.SiteAdmins;

/**
 * Designed to support sending multiple messages from a single connection for speed.
 * 
 * @author Keith Watson
 *
 */

public class Mail {

	private IMail mailSession;


	public void send(String from, String recipients, String subject, String body) throws MessagingException, NamingException {

		try {

			/* Don't send an email out if this is a test server, just output to standard out. */

			if (Configuration.getInstance().isTestServer()) {
				System.out.println(body);
				return;
			}

			/* Check configuration and use appropriate mail */

			if (Configuration.getInstance().isEmailSsl()) {

				if (this.mailSession == null) {
					SslSmtpMail mailSession = new SslSmtpMail(Configuration.getInstance().getSmtpServerLoginId(), Configuration.getInstance().getSmtpServerPassword(), Configuration.getInstance().getSmtpServer(), Configuration.getInstance().getSmtpPort());
					this.mailSession = mailSession;
				}

				this.mailSession.send(from, recipients, subject, body);

			} else {

				if (this.mailSession == null) {
					SmtpMail mailSession = new SmtpMail(Configuration.getInstance().getSmtpServer());
					this.mailSession = mailSession;
				}

				this.mailSession.send(from, recipients, subject, body);
			}
			
		} catch (AddressException e) {
			Logger.log(new Date(), "Failed to send mail to : *" + recipients + "*" +"<br />" + e.getMessage(), null, LogMessageType.SYSTEM);
		}
		
	}


	/**
	 * This is a little slow, but we don't expect there to be many site admins
	 */

	public void sendToSiteAdmins(String subject, String body) throws SQLException, NamingException, MessagingException {

		/* Get the site admins */

		List<String> siteAdmins = SiteAdmins.getSiteAdmins();

//		/* Override for now - get rid of the site admins and just mail me until I fix things */
//
//		siteAdmins.clear();
//		siteAdmins.add("keithmatthewwatson@gmail.com");

		/* Loop around them all and send emails */

		for (String siteAdmin : siteAdmins) {
			Mail mail = new Mail();
			mail.send(Configuration.getInstance().getSmtpServerLoginId(), siteAdmin, subject, body);
		}
	}


	public static void main(String[] args) throws Exception {

		Configuration.getInstance().setConnectionStrategy(ConnectionStrategy.StaticConnection);
		Configuration.load();

	}

}
